<?php
namespace app\job;
use think\queue\Job;
use think\Db;
class OrderClose
{
    public function fire(Job $job, $data)
    {
        try {
            $order_id = $data['order_id'];
            var_dump($order_id);
            $whereOrder = [
                ['id','=',$order_id],
                ['status','=',0],
                ['del','=',0]
            ];
            $order_exist = Db::table('mp_food_order')->where($whereOrder)->field('id,status')->find();
            if(!$order_exist) {
                $this->log('CloseOrder/fire',$order_id . ' NOT EXIST');
                $job->delete();
                return;
            }
            Db::startTrans();
            $result = Db::table('mp_food_order')->where($whereOrder)->update(['del'=>1]);
            $whereDetail = [
                ['order_id','=',$order_exist['id']]
            ];
            $detail = Db::table('mp_food_order_detail')->where($whereDetail)->field('food_id,num')->select();
            foreach ($detail as $food) {
                Db::table('mp_food')->where('id','=',$food['food_id'])->setInc('stock',$food['num']);
            }
            Db::commit();
            if($result !== false){
                // 如果执行成功则删除任务
                $this->log('CloseOrder/fire',$order_id . ' ORDER_CLOSE SUCCESS');
                $job->delete();
                return;
            }else{
                // 重复3次都没结束则强制删除任务
                if ($job->attempts() > 3) {
                    $this->log('CloseOrder/fire',$order_id . ' 3 TIMES REPEAT, AUTO CLOSED');
                    $job->delete();
                    return;
                }else{
                    // 延迟10秒钟再执行一次这个任务
                    $job->release(10);
                }
            }
        } catch (\Exception $e) {
            Db::rollback();
            $this->log('CloseOrder/fire',var_export($data,true));
            $this->log('CloseOrder/fire:Exception',$e->getMessage());
            $job->delete();
            return;
        }

    }
    public function failed($data)
    {

        // ...任务达到最大重试次数后，失败了
    }

    //日志
    private function log($cmd,$str,$filename='OrderQueue.log') {
        $file= dirname(dirname(__DIR__)) . '/log/' . $filename;
        create_dir($file);
        $text='[Time ' . date('Y-m-d H:i:s') ."]\ncmd:" .$cmd. "\n" .$str. "\n---END---" . "\n";
        if(false !== fopen($file,'a+')){
            file_put_contents($file,$text,FILE_APPEND);
        }else{
            echo '创建失败';
        }
    }
}